package cn.chencaiju.day07;

import org.junit.Test;

public class StringTest {
	@Test public void testString() {
		String a="chencaiju";
		String b="chencaiju";
		System.out.println(a==b);
		System.out.println(a.hashCode()+" "+b.hashCode());
	}
	@Test public void testTraverse() {
		String a="chencaiju";
		for(int i=0;i<a.length();i++) {
			System.out.print(a.charAt(i));
		}		
	}
	@Test public void testArray2String() {
		char[] ch= {'农','夫','山','泉','有','点','甜'};
		String str="";
		for(int i=0;i<ch.length;i++) {
			str+=ch[i];
		}
		System.out.println(str);
		System.out.println(ch.toString());
	}
	
	/**
	 * 判断str字符串里面是否含有child字符串
	 * @param str
	 * @param child
	 * @return
	 */
	public boolean isChildStr(String str,String child) {
		char[] cstr=str.toCharArray();
		char[] ch=child.toCharArray();
		int indexOfch=0;
		for(int i=0;i<cstr.length;i++) {
			if(ch[indexOfch]==cstr[i]) {
				indexOfch++;
				if(indexOfch>=ch.length) {
					return true;
				}
			}else {
				indexOfch=0;
			}
		}
		return false;
	}
	@Test public void testIsChildStr() {
		String str="有志者，事竟成，破釜成舟，百二秦关终属楚。";
		String child="者，事竟成";
		
		System.out.println(isChildStr("",""));
	}
	
	/**
	 * 求子串索引
	 * @param str
	 * @param child
	 * @return
	 */
	public int getIndex(String str,String child) {
		char[] cstr=str.toCharArray();
		char[] ch=child.toCharArray();
		int indexOfch=0;
		for(int i=0;i<cstr.length;i++) {
			if(ch[indexOfch]==cstr[i]) {
				indexOfch++;
				if(indexOfch>=ch.length) {
					return 1+i-ch.length;
				}
			}else {
				indexOfch=0;
			}
		}
		return -1;
	}
	@Test public void testGetIndex() {
		String str="苦心人，天不负，卧薪尝胆，三千越甲可吞吴";
		String child="三千越甲可吞吴。";
		
		System.out.println(getIndex(str,child));
	}
	
	public char[] getLastWord(String str) {
		char[] ch=str.toCharArray();
		int index=ch.length-1;
		while(index>=0&&ch[index]==' ') {
			index--;
		}
		int len=0;
		for(;index>=0;index--) {
			if(ch[index]!=' ') {
				len++;
			}else {
				break;
			}
		}
		char[] result=new char[len];
		for(int i=0;i<len;i++) {
			result[i]=ch[++index];
		}
		return result;		
	}
	@Test public void testGetLastWord() {
		String str="Slience is the most perfect expression of scorn  ";
		System.out.println(getLastWord(str));		
	}
}
